package com.ssmk.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ssmk.utlis.EventBusMessage;
import com.ssmk.utlis.PermissionsResultListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * MVPPlugin
 *  邮箱 784787081@qq.com
 */

public abstract class MVPBaseFragment<T> extends Fragment implements BaseView<T>{
    private View mFragView;
    private Unbinder mBind;
    private int mRequestCode;
    private PermissionsResultListener mListener;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(mFragView==null){
            mFragView = inflater.inflate(layoutRes(),null);
            mBind = ButterKnife.bind(this, mFragView);

            //配置EventBus
            EventBus.getDefault().register(this);
            initView();
            initdata();
        }
        ViewGroup parent = (ViewGroup) mFragView.getParent();
        if(parent!=null){
            parent.removeView(mFragView);
        }
        return mFragView;
    }

    protected abstract void initdata();

    protected abstract void initView();

    protected abstract int layoutRes();


    /**
     * 获取EventBus传的值
     * @param t
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MyEventData(EventBusMessage t){

    }

    /**
     * 初始化的toolbar
     * @param toolbar
     * 显示toolbar是否显示字条目
     * @param isShow
     * toobar的标题
     * @param title
     */
        protected void  initToolBar(Toolbar toolbar, boolean isShow, String title){
        ((MVPBaseActivity)getActivity()).initToolBar(toolbar,isShow,title);

        }


        @Override
        public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);

        }


        @Override
        public Context getContext() {
        return super.getContext();
    }

        /*   1.
        其他 fragment 继承 BaseFragment 调用 performRequestPermissions 方法
        desc         首次申请权限被用户拒绝后，给用户的提示
        permissions  要申请的权限数组
        code         请求码
        listener  实现的接口
        **/
        public void performRequestPermission(String desc, String[] permissions, int requestCode,PermissionsResultListener listener){
            if (permissions == null && permissions.length == 0){
                return;
            }else {
                mRequestCode = requestCode;
                mListener = listener;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//  M   API23
                    //检查String[]里的每个权限是否申请过
                    if (checkEachSelfPermission(permissions)){
                        //申请权限前判断是否需要声明
                        requestEachPermissions(desc, permissions, requestCode);
                    }else {// 已经申请权限
                        if (mListener != null){
                            mListener.onPermissionGranted();
                        }
                    }
                }else {
                    if (mListener != null){
                        mListener.onPermissionGranted();
                    }
                }
            }
        }
        /*  3....申请权限前判断是否需要声明*/
        private boolean requestEachPermissions(String desc,String[] permissions,int requestCode){
            //需要再次申请的权限
            if (shouldShowRequestPermissionRationale(permissions)){
                //弹出dialog框，提示用户
                showRationaleDialog(desc, permissions, requestCode);
            }else {
                //直接请求权限
                requestPermissions(permissions, requestCode);
            }
            return false;
        }
        //需要在次申请的权限
        private boolean shouldShowRequestPermissionRationale(String[] permissions){
            for (String permission : permissions){
                if (shouldShowRequestPermissionRationale(permission)){
                    return true;
                }
            }
            return false;
        }

        /**
         * 弹出声明的 Dialog
         * @param desc
         * @param permissions
         * @param requestCode
         */
        private void showRationaleDialog(String desc, final String[] permissions, final int requestCode){
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("提示")
                    .setMessage(desc)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            requestPermissions(permissions,requestCode);//请求权限
                        }
                    })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            })
            .setCancelable(false)
            .show();

        }

        /*   2...检查每个权限是否申请过*/
        private boolean checkEachSelfPermission(String[] permissions){
            for(String permission : permissions){
                if (ContextCompat.checkSelfPermission(getActivity(),permission) != PackageManager.PERMISSION_GRANTED){
                    return  true;
                }
            }
            return false;
        }
    /**
     * 申请权限结果的回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode) {
            if (checkEachPermissionsGranted(grantResults)) {
                if (mListener != null) {
                    mListener.onPermissionGranted();
                }
            } else {// 用户拒绝申请权限
                if (mListener != null) {
                    mListener.onPermissionDenied();
                }
            }
        }
    }

    /**
     * 检查回调结果
     * @param grantResults
     * @return
     */
    private boolean checkEachPermissionsGranted(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
}

